const path = require('path');
const express = require('express');
const nunjucks = require('nunjucks');
const morgan = require('morgan');
const session = require( 'express-session' );

const indexRouter = require('./routes/index');
const customerRouter = require('./routes/customer');
const topicRouter = require('./routes/topic');
const commentRouter = require('./routes/comment');
const uploadRouter = require('./routes/upload');

const port = 8080 ;
const app = express();

// 设置模板引擎
app.set( 'view engine' , 'njk' );
const viewDir = 'views' ;
app.set( 'views' , path.resolve( __dirname, viewDir ) );
nunjucks.configure( viewDir , { autoescape: true , express: app , noCache: true } );

let env = new nunjucks.Environment();
env.addFilter( 'dateformat' , (str)=>{
    console.log( str );
    let dt = new Date( str );
    let year = dt.getFullYear();
    let month = dt.getMonth() + 1 ;
    let date = dt.getDate();
    let hours = dt.getHours();
    let minutes = dt.getMinutes();
    let seconds = dt.getSeconds();
    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
});

env.express( app );

let options = {
    name: 'KFMID',
    secret: 'kaifamiao',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false , path: '/' }
}
app.use( session(options) ); // 提供会话支持
app.use( morgan('dev') );
app.use( express.static( 'public' ) );
app.use( express.json() );
app.use( express.urlencoded({ extended: false }) );


app.use( indexRouter );
app.use( customerRouter );
app.use( topicRouter );
app.use( commentRouter );
app.use( uploadRouter );

app.listen( port );
